<template>
	<div class='box'>
		<u-navbar title="拼团详情"></u-navbar>
		<u-alert-tips type="warning" v-if="disabled" :title="promotionStatus | promotionStatus" :show-icon="true">
		</u-alert-tips>
		<div>
			<u-form label-position='top' :model="form" ref="uForm">
				<u-form-item prop="promotionName" label="活动名称">
					<div>
						<u-input maxlength='25' :disabled="disabled" :custom-style="inputStyle"
							v-model="form.promotionName" />
						<div class='tips'>
							活动名称将显示在对人拼团活动列表中，方便商家管理使用，最多输入25个字符
						</div>
					</div>
				</u-form-item>
				<div class='select-goods' v-if='!disabled' @click='selectGoods'>
					选择商品
				</div>
				<!-- 新选择 商品部分 -->
				<div class='goods-flex' v-if="selectedGoodsList.length">
					<div class="goods-item flex" v-for="(item,index) in selectedGoodsList" :key="index">

						<div>
							<u-image width="200" height="200" :src="item.thumbnail"></u-image>
						</div>
						<div class="goods-name">
							<div class="wes-2">{{item.goodsName}}</div>
							<div>库存：{{item.quantity}}</div>
							<div class="goods-price">
								价格：¥ <u-number-box v-model="item.price" :disabled="disabled"></u-number-box>
							</div>
							<div class="delete" @click='selectedGoodsList.splice(index,1)'>
								删除
							</div>
							<u-line color="#ededed" />
						</div>

					</div>
				</div>


				<!-- 之前选择 商品部分 -->
				<div class='goods-flex'>
					<div class="goods-item flex" v-for="(item,index) in form.promotionGoodsList" :key="index">

						<div>
							<u-image width="200" height="200" :src="item.thumbnail"></u-image>
						</div>
						<div class="goods-name">
							<div class="wes-2">{{item.goodsName}}</div>
							<div>库存：{{item.quantity}}</div>
							<div class="goods-price">
								价格：¥ <u-number-box v-model="item.price" :disabled="disabled"></u-number-box>
							</div>
							<div class="delete" @click='form.promotionGoodsList.splice(index,1)'>
								删除
							</div>
							<u-line color="#ededed" />
						</div>
					</div>
				</div>
				<!-- 结束 -->
				<u-form-item prop="startTime" label="活动时间-开始">
					<u-input style="width: 100%;" disabled @click="clickTime('startTime')" :custom-style="inputStyle"
						v-model="form.startTime" />
				</u-form-item>
				<u-form-item prop="endTime" label="活动时间-结束">
					<u-input style="width: 100%;" disabled @click="clickTime('endTime')" :custom-style="inputStyle"
						v-model="form.endTime" />
				</u-form-item>
				<u-form-item label="参团人数">
					<div>
						<u-number-box :min='2' :max="10" :disabled="disabled" v-model="form.requiredNum"></u-number-box>
						<div class='tips'>
							参团人数不少于2人，不得超过10人。
						</div>
					</div>
				</u-form-item>
				<u-form-item label="限购数量">
					<div>
						<u-number-box v-model="form.limitNum" :disabled="disabled"></u-number-box>
						<div class='tips'>
							如果设置为0则视为不限制购买数量
						</div>
					</div>
				</u-form-item>
				<u-form-item label="虚拟成团">
					<div>
						<u-switch :disabled="disabled" v-model="form.fictitious"></u-switch>
						<div class='tips'>
							开启虚拟成团后，24小时人数未满的团，系统将会模拟匿名买家凑满人数，使该团成团；您只需要对已付款参团的真实买家发货；建议合理开启以提高
						</div>
					</div>
				</u-form-item>
				<u-form-item label="拼团规则">
					<div>
						<u-input :disabled="disabled" type="textarea" maxlength='255' :custom-style="inputStyle"
							v-model="form.pintuanRule" />
						<div class='tips'>
							拼团规则描述不能为空且不能大于255个字，会在WAP拼团详情页面显示
						</div>
					</div>
				</u-form-item>

				<div class='submit' v-if='!disabled' @click='submit'>
					保存/提交
				</div>

			</u-form>
			<!-- 时间选择器 -->
			<u-picker mode="time" :disabled="disabled" :start-year="minStratTime" @confirm="callbackTime"
				v-model="showTimePicker" :params="params"></u-picker>

		</div>
	</div>
</template>
<script>
	import {
		savePinTuan,
		editPinTuan,
		getPinTuanDetail
	} from "@/api/promotion";
	import storage from "@/utils/storage.js"; //缓存
	export default {
		data() {
			return {
				times: "",
				params: {
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
					second: false
				},
				showTimePicker: false, // 显示时间选择器

				disabled: false, // 表单input禁用状态

				promotionStatus: "", // 活动状态
				selectedGoodsList: [], //当前选择的商品列表
				form: {
					promotionName: "", // 活动名称
					pintuanRule: "", // 拼团规则
					requiredNum: 2, // 参团人数
					fictitious: false, // 虚拟成团 
					limitNum: 10, //限购数
					promotionGoodsList: [], //活动商品列表
					startTime: "",
					endTime: "",
				},
				rules: {
					promotionName: [{
						required: true,
						message: "活动名称不能为空"
					}],
					startTime: [{
						required: true,
						message: "请选择活动时间"
					}],
					endTime: [{
						required: true,
						message: "请选择结束时间"
					}],
				},
				submitLoading: false, // 添加或编辑提交状态
				options: {
					// 不可选取时间
					disabledDate(date) {
						return date && date.valueOf() < Date.now() - 86400000;
					},
				},
				timeType: "",
				inputStyle: {
					background: "#f7f7f7",
					"padding-left": "20rpx",
					"border-radius": "10rpx",
				},
				minStratTime: new Date().getFullYear(),
				routerVal: "",

			}
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		mounted() {
			this.init();
		},
		onLoad(options) {
			this.routerVal = options
		},
		onShow() {
			uni.$on("selectedGoods", res => {
				this.selectedGoodsList = res
				uni.$off('selectedGoods'); // 清除监听
			})
		},
		methods: {

			// 选择商品
			selectGoods() {
				// 最新选择的商品传给商品列表页面
				const ids = this.selectedGoodsList.map(item => {
					return item.id || item.skuId
				})
				uni.navigateTo({
					url: `/pages/goods/skuList?selected=1&ids=${ids}`
				})
			},

			// 初始化拼团信息
			async init() {
				uni.showLoading({
					title: '加载中'
				})
				const res = await getPinTuanDetail({
					id: this.routerVal.id
				})
				uni.hideLoading()
				if (res.data.success) {
					const result = res.data.result
					// Object.keys(this.form).forEach(item => {
					// 	this.form[item] = res.data.result[item]
					// })
					this.form = res.data.result

					this.promotionStatus = res.data.result.promotionStatus
					this.disabled = res.data.result.promotionStatus != 'NEW'
				}
			},

			// 修改/保存拼团
			submit() {
				this.$refs.uForm.validate(async valid => {
					if (valid) {
						uni.showLoading({
							title: '加载中'
						})
						let res
						// 编辑
						if (this.routerVal.id) {
							this.form.id = this.routerVal.id
							const params = JSON.parse(JSON.stringify(this.form))
							let newGoods = JSON.parse(JSON.stringify(this.selectedGoodsList))
							newGoods = newGoods.map(e => {
								return {
									categoryPath: e.categoryPath,
									endTime: params.endTime,
									goodsId: e.goodsId,
									goodsName: e.goodsName,
									goodsType: e.goodsType,
									originalPrice: e.price,
									price: e.price,
									promotionId: params.id,
									quantity: e.quantity,
									skuId: e.id,
									startTime: params.startTime,
									storeId: e.storeId,
									thumbnail: e.thumbnail,
									skuId: e.id,
								}
							})

							params.promotionGoodsList.unshift(...newGoods)

							res = await editPinTuan(params)
						} else {
							// 保存
							res = await savePinTuan(this.form);
						}
						uni.hideLoading()
						if (res.data.success) {
							uni.showToast({
								title: `${this.routerVal.id ? '编辑' : '添加'}成功`,
								icon: 'none'
							})
							uni.$emit("refresh");
							setTimeout(() => {
								uni.navigateBack()
							}, 1000)
						}
					}
				});
			},

			clickTime(type) {
				if (this.disabled) return
				this.showTimePicker = true
				this.timeType = type
			},

			// 选择器回调时间
			callbackTime(val) {
				const time = `${val.year}-${val.month}-${val.day} ${val.hour}:${val.minute}:00`
				this.form[this.timeType] = time
			}
		}
	}
</script>
<style scoped lang="scss">
	.box {
		padding: 16rpx;
		padding-bottom: 100rpx;
	}



	.tips {
		font-size: 24rpx;
		color: #999;
		margin: 20rpx 0;
		line-height: 1.5;
	}

	.select-goods {
		background: #333;
		color: #fff;
		width: 200rpx;
		height: 60rpx;
		line-height: 60rpx;
		text-align: center;
		border-radius: 10rpx;
		margin: 20rpx 0;
	}

	.goods-item {
		padding: 32rpx 0;
	}

	.goods-price {
		text-align: right;
	}

	.goods-name {
		flex: 2;
		margin-left: 20rpx;
	}

	.goods-total {
		display: flex;
		flex-direction: column;
		margin-top: 20rpx;

		>.flex {
			justify-content: space-between;
			margin: 10rpx 0;
			line-height: 1.75;

			>div:nth-of-type(1) {
				font-size: 24rpx;
				color: #999;
			}

			>div:nth-of-type(2) {
				font-weight: bold;

				>span {
					font-size: 40rpx;
					margin-left: 10rpx;
				}
			}

			>div {
				margin: 0 4rpx;
				display: flex;
				align-items: center;
				justify-content: flex-end;
			}
		}
	}

	.submit {
		position: fixed;
		bottom: 10rpx;
		width: 90%;
		left: 5%;
		z-index: 99;
	}

	.delete {
		color: $main-color;
		margin: 20rpx 0;
		text-align: right;
	}
</style>
